package com.jsu.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsu.client.UserClient;
import com.jsu.config.RedisCache;
import com.jsu.mapper.*;
import com.jsu.service.ActivityService;
import com.jsu.utils.Base64Utils;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.ext.toc.TocExtension;
import com.vladsch.flexmark.util.ast.Document;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import org.example.model.activity.dto.AcFlowWithSpeakerDTO;
import org.example.model.activity.dto.ActivityWithFlowDTO;
import org.example.model.activity.pojo.*;
import org.example.model.common.dtos.ResponseResult;
import org.example.model.common.enums.WebHttpCodeEnum;
import org.example.model.user.pojo.Speaker;
import com.jsu.common.exception.CustomException;
import org.example.model.user.pojo.UserCheckin;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.imgproc.Imgproc;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.example.model.common.enums.RedisCodeEnum.ACTIVITY;

import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.data.MutableDataSet;
import org.springframework.transaction.annotation.Transactional;


@Service
@Slf4j
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityArticleMapper activityArticleMapper;

    @Autowired
    private ActivityFlowMapper activityFlowMapper;
    @Autowired
    private FlowSpeakerMapper flowSpeakerMapper;
    @Autowired
    private SpeakerMapper speakerMapper;
    @Autowired
    private RegistrationMapper registrationMapper;
    @Autowired
    private ActivityLikeMapper activityLikeMapper;
    @Autowired
    private ActivitySubMapper activitySubMapper;
    @Autowired
    private UserCheckInMapper userCheckInMapper;
    @Autowired
    private RedisCache redisCache;

    @Autowired(required = false)
    private UserClient userClient;

    @Override
    public ResponseResult getAllActivities(Integer type,Integer userId) {
        //String key = ACTIVITY.getMsg() + "user:" + userId;
        /*if(type==null){
            List<ActivityWithFlowDTO> list = redisCache.getCacheList(key);
            if (!list.isEmpty()) {
                return ResponseResult.okResult(list);
            }
        }*/

        // 获取2024年的议程列表
        LocalDate startTime = LocalDate.of(2024, 1, 1);
        LocalDate endTime = LocalDate.of(2024, 12, 31);
        LambdaQueryWrapper<Activity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //sql语句
        lambdaQueryWrapper.between(Activity::getActivityDate, startTime, endTime);
        if(type!=null){
            lambdaQueryWrapper.eq(Activity::getType,type);
        }

        List<Activity> activityList = activityMapper.selectList(lambdaQueryWrapper);

        // 获取流程列表
        List<ActivityFlow> flowList = activityFlowMapper.selectList(null);

        // 根据活动ID分组流程，并为每个流程添加演讲人信息
        Map<Integer, List<AcFlowWithSpeakerDTO>> collect = flowList.stream()
                .collect(Collectors.groupingBy(ActivityFlow::getActivityId,
                        Collectors.mapping(flow -> getFlowWithSpeakerDTO(flow), Collectors.toList())));

        //拿到用户活动订阅信息
        Map<Integer, ActivitySub> activitySub = getActivitySub(userId);
        // 转换为DTO对象
        List<ActivityWithFlowDTO> activityWithFlowDTOList = activityList.stream()
                .map(item -> {
                    ActivityWithFlowDTO activityWithFlowDTO = new ActivityWithFlowDTO();
                    activityWithFlowDTO.setFlows(collect.getOrDefault(item.getPkId(), Collections.emptyList()));
                    BeanUtils.copyProperties(item, activityWithFlowDTO);
                    //设置用户是否订阅
                    activityWithFlowDTO.setState(activitySub.containsKey(item.getPkId())?1:0);
                    return activityWithFlowDTO;
                }).collect(Collectors.toList());

        log.info("4");
        // 缓存结果
        if (activityWithFlowDTOList.isEmpty()){
            return ResponseResult.okResult("活动为空");
        }
        //用户登录，推荐活动
        if (userId!=null){
            activityWithFlowDTOList = recommendActivities(activityWithFlowDTOList,userId);
        }
        //redisCache.setCacheList(key, activityWithFlowDTOList);
        return ResponseResult.okResult(activityWithFlowDTOList);
    }

    private Map<Integer, ActivitySub> getActivitySub(Integer userId){
        LambdaQueryWrapper<ActivitySub> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ActivitySub::getUserId,userId)
                .eq(ActivitySub::getSubscribed,1);//只查询已订阅的
        List<ActivitySub> activitySub = activitySubMapper.selectList(lambdaQueryWrapper);
        //转化为map,<活动id，订阅信息>
        Map<Integer, ActivitySub> map = activitySub.stream().collect(Collectors.toMap(ActivitySub::getActivityId, item -> item));

        return map;
    }

    private AcFlowWithSpeakerDTO getFlowWithSpeakerDTO(ActivityFlow flow) {
        List<FlowSpeaker> flowSpeakers = getFlowSpeakers(flow.getPkId());
        List<Speaker> speakers = flowSpeakers.stream()
                .map(flowSpeaker -> getSpeaker(flowSpeaker.getSpeakerId()))
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
        AcFlowWithSpeakerDTO flowWithSpeakerDTO = new AcFlowWithSpeakerDTO();
        flowWithSpeakerDTO.setPkId(flow.getPkId());
        flowWithSpeakerDTO.setActivityId(flow.getActivityId());
        flowWithSpeakerDTO.setContent(flow.getContent());//设置流程内容
        flowWithSpeakerDTO.setStartTime(flow.getStartTime());
        flowWithSpeakerDTO.setEndTime(flow.getEndTime());
        flowWithSpeakerDTO.setSpeakers(speakers);
        return flowWithSpeakerDTO;
    }

    private List<FlowSpeaker> getFlowSpeakers(Integer flowId) {
        LambdaQueryWrapper<FlowSpeaker> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FlowSpeaker::getType, 2).eq(FlowSpeaker::getFlowId, flowId);
        return flowSpeakerMapper.selectList(lambdaQueryWrapper);
    }

    private Optional<Speaker> getSpeaker(Integer speakerId) {
        return Optional.ofNullable(speakerMapper.selectById(speakerId));
    }

    /**
     * 基于活动浏览量和用户相关点赞信息的智能推荐算法
     * @param activityList 活动
     * @param userId 用户id
     * @return
     */
    private List<ActivityWithFlowDTO> recommendActivities(List<ActivityWithFlowDTO> activityList,Integer userId){
        //获取用户点赞数据
        LambdaQueryWrapper<ActivityLike> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ActivityLike::getUserId,userId);
        List<ActivityLike> activityLikes = activityLikeMapper.selectList(lambdaQueryWrapper);

        //计算活动权重,<活动id，权重值>
        Map<Integer,Integer> activityWeight = new HashMap<>();
        for (ActivityWithFlowDTO activityWithFlowDTO : activityList) {
            int weight = calWeight(activityWithFlowDTO);
            activityWeight.put(activityWithFlowDTO.getPkId(),weight);
        }
        //计算用户活动偏好
        Map<Integer,Integer> userLikes = new HashMap<>();
        for (ActivityLike activityLike : activityLikes) {
            Integer activityId = activityLike.getActivityId();
            userLikes.put(activityId,userLikes.getOrDefault(activityId,0) + 1);
        }
        //根据活动权重和用户偏好进行推荐
        Map<Integer,Double>  recommendActivities = new HashMap<>();
        for (ActivityWithFlowDTO activityWithFlowDTO : activityList) {
            int weight = activityWeight.getOrDefault(activityWithFlowDTO.getPkId(),50);
            int userLike = userLikes.getOrDefault(activityWithFlowDTO.getPkId(),10);
            //
            double score = weight * userLike;
            recommendActivities.put(activityWithFlowDTO.getPkId(),score);
        }
        // 根据推荐分数对活动列表进行排序
        List<ActivityWithFlowDTO> sortedActivityList = activityList.stream()
                .sorted(Comparator.comparingDouble(ActivityWithFlowDTO::getPkId)
                        .reversed()) // 按照推荐分数降序排序
                .collect(Collectors.toList());
        return sortedActivityList;

    }

    private int calWeight(ActivityWithFlowDTO activityWithFlowDTO) {
        //计算权重，以浏览量+点赞量为权重值
        return activityWithFlowDTO.getLooking()+activityWithFlowDTO.getLikes();
    }


    @Override
    public ResponseResult getActivityByName(Integer type) {
        List<Object> cacheList = redisCache.getCacheList(ACTIVITY.getMsg() +"type:"+ type);
        if(!cacheList.isEmpty()){
            return ResponseResult.okResult(cacheList);
        }
        LambdaQueryWrapper<Activity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Activity::getType,type);
        List<Activity> activities = activityMapper.selectList(lambdaQueryWrapper);
        if (activities.isEmpty()){
            return ResponseResult.okResult("活动为空");
        }
        List<ActivityWithFlowDTO> collect = activities.stream().map(item -> {
            ActivityWithFlowDTO activityDTO = new ActivityWithFlowDTO();
            BeanUtils.copyProperties(item, activityDTO);
            return activityDTO;
        }).collect(Collectors.toList());
        String key = ACTIVITY.getMsg()+"type:"+type;
        redisCache.setCacheList(key,collect);
        return ResponseResult.okResult(collect);
    }

    @Override
    public ResponseResult getActivityById(Integer activityId) {
        Activity activity = activityMapper.selectById(activityId);
        if (!Objects.isNull(activity)){
            return ResponseResult.okResult(activity);
        }
        return ResponseResult.errorResult(400,"活动不存在");
    }

    @Override
    public ResponseResult getArticleToHtml(Integer activityId) {
        LambdaQueryWrapper<ActivityArticle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ActivityArticle::getActivityId,activityId);
        ActivityArticle activityArticle = activityArticleMapper.selectOne(lambdaQueryWrapper);
        if(Objects.isNull(activityArticle)){
            throw new RuntimeException("文章为空");
        }

        MutableDataSet options = new MutableDataSet();
        //TOC目录解析,表格解析
        options.set(Parser.EXTENSIONS, Arrays.asList(TocExtension.create(), TablesExtension.create()));

        Parser parser = Parser.builder(options).build();
        Document document = parser.parse(activityArticle.getActivityContent());

        HtmlRenderer renderer = HtmlRenderer.builder(options).build();
        String html = renderer.render(document);
        html = html.replace("\n","");
        return ResponseResult.okResult(html);
    }

    @Override
    public ResponseResult updateActivityLikes(Integer activityId,Integer userId,Integer isLiked) {

        Activity activity = activityMapper.selectById(activityId);
        if(Objects.isNull(activity)){
            throw new RuntimeException("活动不存在");
        }
        if (isLiked==1){
            activity.setLikes(activity.getLikes()+1);
            activityMapper.updateById(activity);
        }
        else {
            activity.setLikes(activity.getLikes()-1);
            activityMapper.updateById(activity);
        }

        //存入用户活动点赞数据库
        LambdaQueryWrapper<ActivityLike> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ActivityLike::getActivityId,activityId)
                .eq(ActivityLike::getUserId,userId);
        ActivityLike activityLike = activityLikeMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(activityLike)){
            ActivityLike activityLike1 = new ActivityLike();
            activityLike1.setActivityId(activityId);
            activityLike1.setLikeTime(new Date());
            activityLike1.setIsLiked(1);
            activityLike1.setUserId(userId);
            activityLikeMapper.insert(activityLike1);//插入点赞表
        }
        else {
            activityLike.setLikeTime(new Date());
            activityLike.setIsLiked(isLiked);
            activityLikeMapper.updateById(activityLike);//更新
            return ResponseResult.okResult(isLiked);
        }

        String key = ACTIVITY.getMsg() + activityId;
        redisCache.deleteObject(key);
        redisCache.setCacheObject(key, JSON.toJSONString(activity));
        return ResponseResult.okResult("操作成功");
    }


    @Override
    public ResponseResult addActivityViews(Integer activityId) {
        Activity activity = activityMapper.selectById(activityId);
        if (Objects.isNull(activity)){
            throw new RuntimeException("活动不存在");
        }
        activity.setLooking(activity.getLooking()+1);
        activityMapper.updateById(activity);
        String key = ACTIVITY.getMsg() + activityId;
        redisCache.deleteObject(key);
        redisCache.setCacheObject(key,JSON.toJSONString(activity));
        return ResponseResult.okResult("浏览成功");
    }

    /**
     * 活动报名
     * @param registration
     * @return
     */
    @Override
    public ResponseResult registration(Registration registration) {
        LambdaQueryWrapper<Registration> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Registration::getActivityId,registration.getActivityId())
                .eq(Registration::getUserId,registration.getUserId());
        Registration registration1 = registrationMapper.selectOne(lambdaQueryWrapper);
        if (!Objects.isNull(registration1)){
            throw new RuntimeException("该活动用户已报名，请不要重复报名");
        }
        registration.setTime(new Date());
        registrationMapper.insert(registration);

        return ResponseResult.okResult("报名成功");
    }

    @Override
    public ResponseResult getAllActivityBasic() {
        List<Activity> activityList = activityMapper.selectList(null);

        return ResponseResult.okResult(activityList);
    }




    /*public ResponseResult getPicture(Integer activityId, HttpServletResponse response) {
        Activity activity = activityMapper.selectById(activityId);
        if(Objects.isNull(activity) && StringUtils.isNotBlank(activity.getPicture())){
            throw new CustomException(WebHttpCodeEnum.DATA_NOT_EXIST);
        }
        ActivityWithFlowDTO activityDTO = new ActivityWithFlowDTO();
        BeanUtils.copyProperties(activity,activityDTO);

        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream=new FileInputStream(new File(activityDTO.getPicture()));
            //输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();


            byte[] bytes=new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
            return ResponseResult.okResult("显示成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST);
    }*/

    @Override
    @Transactional
    public ResponseResult addActivity(ActivityWithFlowDTO activityWithFlowDTO) {
        //先把dto拆开，拿到activity对象和flowspeaker对象，在分别存储到各表去
        if (Objects.isNull(activityWithFlowDTO)) {
            return ResponseResult.errorResult(400, "活动实体为空，新增失败");
        }
        String key = ACTIVITY.getMsg() + activityWithFlowDTO.getPkId();
        activityWithFlowDTO.setLikes(0);//设置点赞量浏览量为0
        activityWithFlowDTO.setLooking(0);
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityWithFlowDTO, activity);
        activityMapper.insert(activity);
        try {
            //有流程演讲在里面
            if (activityWithFlowDTO.getFlows() != null && !activityWithFlowDTO.getFlows().isEmpty()) {
                for (AcFlowWithSpeakerDTO flow : activityWithFlowDTO.getFlows()) {
                    //插入活动流程表
                    flow.setActivityId(activityWithFlowDTO.getPkId());
                    activityFlowMapper.insert(flow);
                    //插入流程演讲人信息
                    for (Speaker speaker : flow.getSpeakers()) {
                        FlowSpeaker flowSpeaker = new FlowSpeaker();
                        flowSpeaker.setFlowId(flow.getPkId());
                        flowSpeaker.setType(2);//设为activity型的流程演讲表
                        flowSpeaker.setSpeakerId(speaker.getPkId());//设演讲人id
                        flowSpeakerMapper.insert(flowSpeaker);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("数据有问题，新增失败");
        }
        redisCache.setCacheObject(key, JSON.toJSONString(activityWithFlowDTO));
        return ResponseResult.okResult("新增活动成功");
    }

    @Override
    @Transactional
    public ResponseResult delActivity(Integer activityId) {
        try {
            Activity activity = activityMapper.selectById(activityId);
            if (Objects.isNull(activity)) {
                return ResponseResult.errorResult(400, "活动不存在，删除失败");
            }

            // 删除活动流程演讲人信息
            LambdaQueryWrapper<ActivityFlow> flowWrapper = new LambdaQueryWrapper<>();
            flowWrapper.eq(ActivityFlow::getActivityId, activityId);
            List<ActivityFlow> activityFlows = activityFlowMapper.selectList(flowWrapper);
            for (ActivityFlow activityFlow : activityFlows) {
                LambdaQueryWrapper<FlowSpeaker> speakerWrapper = new LambdaQueryWrapper<>();
                speakerWrapper.eq(FlowSpeaker::getFlowId, activityFlow.getPkId());
                flowSpeakerMapper.delete(speakerWrapper);
                LambdaQueryWrapper<FlowSpeaker> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(FlowSpeaker::getType,2)
                        .eq(FlowSpeaker::getFlowId,activityFlow.getPkId());
                flowSpeakerMapper.delete(lambdaQueryWrapper);
            }

            // 删除活动流程
            activityFlowMapper.delete(flowWrapper);

            // 删除活动
            activityMapper.deleteById(activityId);

            // 删除缓存
            String key = ACTIVITY.getMsg() + activityId;
            redisCache.deleteObject(key);

            return ResponseResult.okResult("活动删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("活动删除失败");
        }
    }

    @Override
    @Transactional
    public ResponseResult updateActivity(ActivityWithFlowDTO activityWithFlowDTO) {
        if (Objects.isNull(activityWithFlowDTO)){
            return ResponseResult.errorResult(400,"活动实体为空，更新失败");
        }
        String key = ACTIVITY.getMsg() + activityWithFlowDTO.getPkId();
        redisCache.deleteObject(key);
        redisCache.setCacheObject(key,JSON.toJSONString(activityWithFlowDTO));

        Activity activity = new Activity();
        BeanUtils.copyProperties(activityWithFlowDTO,activity);
        log.info(String.valueOf(activity));
        activityMapper.updateById(activity);
        try {
            List<AcFlowWithSpeakerDTO> flows = activityWithFlowDTO.getFlows();

            // 先删
            LambdaQueryWrapper<ActivityFlow> flowWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<FlowSpeaker> speakerWrapper = new LambdaQueryWrapper<>();
            flowWrapper.eq(ActivityFlow::getActivityId, activityWithFlowDTO.getPkId());
            List<ActivityFlow> activityFlows = activityFlowMapper.selectList(flowWrapper);
            activityFlowMapper.delete(flowWrapper);
            for (ActivityFlow activityFlow : activityFlows) {
                speakerWrapper.eq(FlowSpeaker::getType,2)
                        .eq(FlowSpeaker::getFlowId, activityFlow.getPkId());
                flowSpeakerMapper.delete(speakerWrapper);
            }
            //后增
            for (AcFlowWithSpeakerDTO flow : flows) {
                activityFlowMapper.insert(flow);
                for (Speaker speaker : flow.getSpeakers()) {
                    FlowSpeaker flowSpeaker = new FlowSpeaker();
                    flowSpeaker.setSpeakerId(speaker.getPkId());
                    flowSpeaker.setType(2);
                    flowSpeaker.setFlowId(flow.getPkId());
                    flowSpeakerMapper.insert(flowSpeaker);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("activity更新失败");
        }

        return ResponseResult.okResult("更新活动成功");
    }

    @Override
    public ResponseResult takePhoto(Integer activityId, Integer userId, String base64Img) {
        Mat mat1 = null;
        Mat mat2 = null;
        mat1 = Base64Utils.base64ToMat(base64Img);
        List<String> imageFilesInFolder = getImageFilesInFolder();
        for (String s : imageFilesInFolder) {
            try {
                mat2 = Base64Utils.matURL(new URL(s));

                // 将图片处理成一样大
                Imgproc.resize(mat1, mat1, mat2.size());
                Imgproc.resize(mat2, mat2, mat1.size());

            } catch (MalformedURLException e) {
                throw new RuntimeException("URL转化base64失败");
            }
            double v = calculateHistogram(mat1, mat2);
            log.info("相似度：" + v);
            if (v>=0.65){
                // 相似度大于0.8，认为是同一张图片
                try {
                    addUserCheckIn(activityId, userId);// 增加签到记录
                } catch (Exception e) {
                    return ResponseResult.errorResult(500,"请勿重复签到");
                }
                return ResponseResult.okResult(200,"图片相似度过高，签到成功");
            }
        }
        return ResponseResult.okResult(500,"图片相似度过低，签到失败");
    }

    @Override
    public ResponseResult getNextActivity(Integer activityId) {
        LambdaQueryWrapper<Activity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Activity::getPkId,activityId)
                .ne(Activity::getType,2);//表示不为直播和支付活动
        Activity activity = activityMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(activity)){

        }
        List<Activity> activities = activityMapper.selectList(null);
        Map<Integer,Activity> map = activities.stream().collect(Collectors.toMap(Activity::getPkId,Function.identity()));
        Set<Integer> remainingIds = map.keySet();

        map.remove(activityId);
        int remainingSize = remainingIds.size();

        // 生成随机索引，范围在 [0, 剩余活动数量)
        int randomIndex = new Random().nextInt(remainingSize);

        // 将 Set 转换为 List，以便通过索引获取对应的 ID
        List<Integer> remainingIdList = new ArrayList<>(remainingIds);

        // 获取随机 ID
        Integer randomId = remainingIdList.get(randomIndex);
        return ResponseResult.okResult(map.get(randomId));
    }

    @Override
    public ResponseResult getRegistrationByActivityId(Integer activityId) {
        LambdaQueryWrapper<Activity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Activity::getPkId,activityId);
        Activity activity = activityMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(activity)){
            return ResponseResult.errorResult(400,"活动不存在");
        }
        return ResponseResult.okResult(activity);
    }

    @Override
    public ResponseResult addArticle(ActivityArticle activityArticle) {

        //先新增活动，具体内容的新增去活动列表里
        Activity activity = new Activity();
        activity.setContentType(1);//设置为海报类型
        activity.setActivityName(activityArticle.getTitle());
        activity.setActivityDate(new Date());

        activityMapper.insert(activity);//插入活动表
        //后新增活动文章
        activityArticle.setActivityId(activity.getPkId());
        activityArticleMapper.insert(activityArticle);//插入活动文章表
        return ResponseResult.okResult("新增活动文章成功");
    }

    /**
     * 活动报名列表查询
     * @return
     */
    @Override
    public ResponseResult getRegistrationList() {
        List<Registration> registrations = registrationMapper.selectList(null);

        return ResponseResult.okResult(registrations);
    }

    @Override
    public ResponseResult getActivitysByName(String activityName) {
        List<ActivityWithFlowDTO> allActivities = (List<ActivityWithFlowDTO>) getAllActivities(null, null).getData();
        List<ActivityWithFlowDTO> activitiesByName = allActivities.stream().filter(activity -> activity.getActivityName().contains(activityName)).collect(Collectors.toList());
        return ResponseResult.okResult(activitiesByName);
    }


    public static List<String> getImageFilesInFolder() {
        String bucketName = "wscc5-1324713586";
        String folderPath = "cos.ap-guangzhou.myqcloud.com";
        List<String> allFiles = new ArrayList<>();
        for (int i = 1; i <= 11; i++) {
            String imageUrl = "https://" + bucketName + "." + folderPath + "/吉祥物/" + i + ".jpg";
            allFiles.add(imageUrl);
        }
        return allFiles;
    }
    // 计算均方差（MSE）
    private static double calculateHistogram(Mat image1, Mat image2) {
        // 计算直方图
        Mat hist1 = calculateHistogram(image1);
        Mat hist2 = calculateHistogram(image2);
        //将图片处理一样大
        Imgproc.resize(image1, image1, image2.size());
        Imgproc.resize(image2, image2, image1.size());

        // 计算相似度
        final double similarity = Imgproc.compareHist(hist1, hist2, Imgproc.CV_COMP_CORREL);
        return similarity;
    }
    private static Mat calculateHistogram(Mat image) {
        Mat hist = new Mat();

        // 设置直方图参数
        MatOfInt histSize = new MatOfInt(256);
        MatOfFloat ranges = new MatOfFloat(0, 256);
        MatOfInt channels = new MatOfInt(0);
        List<Mat> images = new ArrayList<>();
        images.add(image);

        // 计算直方图
        Imgproc.calcHist(images, channels, new Mat(), hist, histSize, ranges);

        return hist;
    }


    private void addUserCheckIn(Integer activityId, Integer userId) {
        // 先查
        LambdaQueryWrapper<UserCheckin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserCheckin::getActivityId, activityId)
                .eq(UserCheckin::getUserId, userId);
        UserCheckin userCheckin = userCheckInMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(userCheckin)) {
            // 再添加
            UserCheckin userCheckin1 = new UserCheckin();
            userCheckin1.setActivityId(activityId);
            userCheckin1.setUserId(userId);
            userCheckin1.setCheckinTime(new Date());
            userCheckInMapper.insert(userCheckin1);
        }
        else {
            throw new RuntimeException("该用户已签到，请勿重复签到");
        }
    }
}
